package me.qingy.shiro.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.qingy.common.constant.ShiroConstants;
import me.qingy.core.entity.User;
import me.qingy.core.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author qingy
 * @since 2021-05-07
 */
@Component
public class LoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordService passwordService;

    public User login(String username, String password) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ShiroConstants.CAPTCHA_ERROR.equals(requestAttributes.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
            throw new AuthenticationException("验证码错误");
        }

        User user = userService.getOne(new QueryWrapper<User>().eq("login_name", username));
        if (user == null) {
            throw new AuthenticationException("登陆失败");
        }

        passwordService.validate(user, password);

        return user;
    }
}
